<template>
  <div>
    <CreditCard ref="componentRef" @complete="onSubmitComplete" />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useCreditCardStore } from '@/store/credit-card'
import { useConfirmData } from '@/compositions/dialog/confirm-data'
import CreditCard from './embed/creditCard.vue'

const creditCardStore = useCreditCardStore()
const { getCreditCardList } = creditCardStore

const componentRef = ref(null)
const submitResult = ref(false)
const intent = ref(null)
const isComplete = ref(false)

function onSubmitComplete({ status, intent: _intent }) {
  submitResult.value = status
  _intent && (intent.value = _intent)
  isComplete.value = true
}

function recallComplete() {
  return new Promise((resolve) => {
    const interval = setInterval(() => {
      if (isComplete.value) {
        clearInterval(interval)
        resolve(submitResult.value)
      }
    }, 500)
  }).then((r) => (r ? { intent: intent.value } : false))
}

useConfirmData(async () => {
  try {
    isComplete.value = false
    const submitBtn = componentRef.value.$el.querySelector('#payment-submit-btn')
    submitBtn.click()
    const result = await recallComplete()
    await getCreditCardList()
    return result
  } catch (e) {
    return false
  }
})
</script>
